"""
@Time    : 2019/10/16 9:21
@Author  : CcH
"""

import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import math
import torch


class LipNet(torch.nn.Module):
    def __init__(self, C, dropout_p1=0.5,dropout_p2=0.2):
        super(LipNet, self).__init__()
        self.conv1 = nn.Conv3d(1, 32, (3, 5, 5), (1, 2, 2), (1, 2, 2))
        self.pool1 = nn.MaxPool3d((1, 2, 2), (1, 2, 2))

        self.conv2 = nn.Conv3d(32, 64, (3, 5, 5), (1, 1, 1), (1, 2, 2))
        self.pool2 = nn.MaxPool3d((1, 2, 2), (1, 2, 2))

        self.conv3 = nn.Conv3d(64, 96, (3, 3, 3), (1, 1, 1), (1, 1, 1))
        self.pool3 = nn.MaxPool3d((1, 2, 2), (1, 2, 2))

        self.conv4 = nn.Conv3d(96, 96, (3, 3, 3), (1, 1, 1), (1, 1, 1))
        self.pool4 = nn.MaxPool3d((1, 2, 2), (1, 2, 2))

        self.gru1 = nn.GRU(96 * 4 * 4, 128, 1, bidirectional=True)
        self.gru2 = nn.GRU(256, 128, 1, bidirectional=True)
        # self.self_attention = SelfAttentionDot(512, 512)
        self.hidden2hidden = nn.Linear(96 * 4 * 4, 512)
        self.FC = nn.Linear(256, C)
        # self.dropout_p = dropout_p
        self.bn_norm = nn.BatchNorm1d(96 * 4 * 4,momentum=0.5)
        self.relu = nn.ReLU(inplace=True)
        # self.relu = nn.ELU(inplace=True)
        self.dropout = nn.Dropout(dropout_p2)
        self.dropout3d = nn.Dropout3d(dropout_p1)
        self.bn_norm1 = nn.BatchNorm1d(256, momentum=0.5)
        self.bn_norm2 = nn.BatchNorm1d(256, momentum=0.5)
        self._init()

    def _init(self):

        init.kaiming_normal_(self.conv1.weight, nonlinearity='relu')
        init.constant_(self.conv1.bias, 0)

        init.kaiming_normal_(self.conv2.weight, nonlinearity='relu')
        init.constant_(self.conv2.bias, 0)

        init.kaiming_normal_(self.conv3.weight, nonlinearity='relu')
        init.constant_(self.conv3.bias, 0)

        init.kaiming_normal_(self.conv4.weight, nonlinearity='relu')
        init.constant_(self.conv4.bias, 0)

        init.kaiming_normal_(self.FC.weight, nonlinearity='sigmoid')
        init.constant_(self.FC.bias, 0)

        for m in (self.gru1, self.gru2):
            stdv = math.sqrt(2 / (96 * 3 * 6 + 128))
            for i in range(0, 128 * 3, 128):
                init.uniform_(m.weight_ih_l0[i: i + 128],
                              -math.sqrt(3) * stdv, math.sqrt(3) * stdv)
                init.orthogonal_(m.weight_hh_l0[i: i + 128])
                init.constant_(m.bias_ih_l0[i: i + 128], 0)
                init.uniform_(m.weight_ih_l0_reverse[i: i + 128],
                              -math.sqrt(3) * stdv, math.sqrt(3) * stdv)
                init.orthogonal_(m.weight_hh_l0_reverse[i: i + 128])
                init.constant_(m.bias_ih_l0_reverse[i: i + 128], 0)

    def forward(self, x):

        x = self.conv1(x)
        x = self.relu(x)
        x = self.dropout3d(x)
        x = self.pool1(x)

        x = self.conv2(x)
        x = self.relu(x)
        x = self.dropout3d(x)
        x = self.pool2(x)

        x = self.conv3(x)
        x = self.relu(x)
        x = self.dropout3d(x)
        x = self.pool3(x)

        # (B, C, T, H, W)->(T, B, C, H, W)
        x = x.permute(2, 0, 1, 3, 4).contiguous()
        # (B, C, T, H, W)->(T, B, C*H*W)
        x = x.view(-1, 96 * 4 * 4)
        x = self.bn_norm(x)
        x = x.view(15, -1, 96*4*4)
        self.gru1.flatten_parameters()
        self.gru2.flatten_parameters()

        # c3dout = self.hidden2hidden(x)
        # out_pool = c3dout.transpose(0, 1).transpose(1, 2)
        # out_pool_avg = F.avg_pool1d(out_pool, out_pool.size(2)).squeeze(2)

        x = self.dropout(x)
        x, h = self.gru1(x)
        x = self.dropout(x)
        # x = self.bn_norm1(x.view(-1, 256))
        # x = x.view(15,-1,256)
        x, h = self.gru2(x)
        x = self.dropout(x)

        # x = torch.cat((gru1_out, x[-1]), dim=1)
        x = x[-1]

        # x = torch.cat((x[0,:,:256],x[-1,:,256:]),dim=1)
        x = self.bn_norm2(x)
        # x = self.hidden2hidden(x)
        x = self.FC(x)
        x = F.log_softmax(x, dim=1)
        return x


if __name__ == '__main__':
    from DataLoader.Picture_Process import file_2_allpicture

    path = r"D:\XW_Bank\LipRecognition\train\mouth_64_train\000c43e99bdceb93a39e729ffc38ac2a"
    input_p = file_2_allpicture(path)
    model = LipNet(313).cuda()
    src = input_p.cuda()
    output = model(src)
    print(output.shape)